import common from '../../../lib/common/common.js'
import {
    getPlayerData,
    getVegetableData,
    isPlayerExist,
    storagePlayerData,
    timestampToSeconds
} from '../l.js'

const REGULAR = [
    /^(#|\/)?种[菜植]\*(\d+)(.*)/,
    /^(#|\/)?(一键|全部)种[菜植](.*)/
]
export class Fs extends plugin {
    constructor() {
        super({
            name: '[Fs]种植',
            dsc: '种植',
            event: 'message',
            priority: 1,
            rule: [
                { reg: REGULAR[0], fnc: 'plant' },
                { reg: REGULAR[1], fnc: 'allPlant' }
            ]
        })
    }
    async plant(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply(['无玩家信息，请发送[领取田地]'])
        }
        const [, , SERIAL_NUMBER, VEGETABLE_NAME, FERTILIZER_NAME] = e.msg.match(/^(#|\/)?种[菜植]\*(\d+)\s*(\S+)(?:\s*施肥\s*(\S+))?/)
        const PLAYER_DATA = await getPlayerData(PLAYER_ID)
        const VEGETABLE_DATA = await getVegetableData()
        const CROP_DATA = VEGETABLE_DATA.find(crop => crop['name'] === VEGETABLE_NAME)
        if (!CROP_DATA) return e.reply(['无此蔬菜，请发送[蔬菜列表]查看喵~'])
        const PLANTING_CYCLE = CROP_DATA['plantingTime'][0] * (CROP_DATA['plantingTime'][1] === '分钟' ? 60 : 3600)

        if (PLAYER_DATA['xp'] < CROP_DATA['needXp']) return e.reply(['xp不足，暂无法种植此作物'])
        if (PLAYER_DATA['frame'].length < SERIAL_NUMBER) return e.reply(['你没有此格子，无法种植喵~'])
        if (PLAYER_DATA['frame'][SERIAL_NUMBER - 1]['start']) return e.reply(['此格子已经有菜了喵~'])
        if (PLAYER_DATA['capital'] < CROP_DATA['price']) return e.reply(['💰不足，无法种植喵~'])

        if (FERTILIZER_NAME) {
            if (!PLAYER_DATA['fertilizer'] || !PLAYER_DATA['fertilizer'][FERTILIZER_NAME]) {
                return e.reply(['您没有这种化肥，请先购买'])
            }
            if (PLAYER_DATA['fertilizer'][FERTILIZER_NAME] <= 0) {
                return e.reply(['化肥数量不足'])
            }

            const fertilizerEffect = {
                '普通化肥': 1.2,
                '高级化肥': 1.5,
                '特级化肥': 2
            }

            PLAYER_DATA['frame'][SERIAL_NUMBER - 1]['fertilizer'] = FERTILIZER_NAME
            PLAYER_DATA['frame'][SERIAL_NUMBER - 1]['number'] = Math.floor(CROP_DATA['harvest'] * fertilizerEffect[FERTILIZER_NAME])
            PLAYER_DATA['fertilizer'][FERTILIZER_NAME]--
        }

        PLAYER_DATA['frame'][SERIAL_NUMBER - 1]['start'] = true
        PLAYER_DATA['frame'][SERIAL_NUMBER - 1]['name'] = VEGETABLE_NAME
        PLAYER_DATA['frame'][SERIAL_NUMBER - 1]['time'] = timestampToSeconds(Date.now()) + PLANTING_CYCLE
        PLAYER_DATA['frame'][SERIAL_NUMBER - 1]['number'] = CROP_DATA['harvest']
        PLAYER_DATA['capital'] -= CROP_DATA['price']
        storagePlayerData(PLAYER_ID, PLAYER_DATA)

        const msg = [
            '种植成功!',
            `格子[${SERIAL_NUMBER}]种下了作物[${VEGETABLE_NAME}]`,
            `${CROP_DATA['plantingTime'].join('')}后可收获喵~`
        ].join('\r')
        return e.reply(msg)
    }

    async allPlant(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply('无玩家信息，请发送[领取田地]')
        }

        // 修改正则以支持施肥
        const [, , , VEGETABLE_NAME, FERTILIZER_NAME] = e.msg.match(/^(#|\/)?(一键|全部)种[菜植]\s*(\S+)(?:\s*施肥\s*(\S+))?$/)
        const PLAYER_DATA = await getPlayerData(PLAYER_ID)
        const VEGETABLE_DATA = await getVegetableData()
        const CROP_DATA = VEGETABLE_DATA.find(crop => crop['name'] === VEGETABLE_NAME)

        if (!CROP_DATA) return e.reply('无此蔬菜，请发送[蔬菜列表]查看喵~')
        if (PLAYER_DATA['xp'] < CROP_DATA['needXp']) return e.reply('xp不足，暂无法种植此作物')

        let emptyPlots = PLAYER_DATA['frame'].filter(frame => !frame['start']).length
        if (emptyPlots === 0) return e.reply('没有空闲的田地喵~')

        const totalPrice = emptyPlots * CROP_DATA['price']
        if (PLAYER_DATA['capital'] < totalPrice) return e.reply(`💰不足，需要${totalPrice}金币`)

        // 检查化肥
        let fertilizerEffect = 1
        if (FERTILIZER_NAME) {
            if (!PLAYER_DATA['fertilizer'] || !PLAYER_DATA['fertilizer'][FERTILIZER_NAME]) {
                return e.reply('您没有这种化肥，请先购买')
            }
            const effects = {
                '普通化肥': 1.2,
                '高级化肥': 1.5,
                '特级化肥': 2
            }
            if (!effects[FERTILIZER_NAME]) {
                return e.reply('没有这种化肥哦，请发送[化肥商店]查看可用化肥')
            }
            if (PLAYER_DATA['fertilizer'][FERTILIZER_NAME] < emptyPlots) {
                return e.reply(`化肥不足，需要${emptyPlots}个${FERTILIZER_NAME}`)
            }
            fertilizerEffect = effects[FERTILIZER_NAME]
        }

        let plantedCount = 0
        const PLANTING_CYCLE = CROP_DATA['plantingTime'][0] * (CROP_DATA['plantingTime'][1] === '分钟' ? 60 : 3600)

        for (let i = 0; i < PLAYER_DATA['frame'].length; i++) {
            if (PLAYER_DATA['frame'][i]['start']) continue;

            PLAYER_DATA['frame'][i] = {
                start: true,
                name: VEGETABLE_NAME,
                time: timestampToSeconds(Date.now()) + PLANTING_CYCLE,
                number: Math.floor(CROP_DATA['harvest'] * fertilizerEffect)
            }

            if (FERTILIZER_NAME) {
                PLAYER_DATA['frame'][i]['fertilizer'] = FERTILIZER_NAME
                PLAYER_DATA['fertilizer'][FERTILIZER_NAME]--
            }

            PLAYER_DATA['capital'] -= CROP_DATA['price']
            plantedCount++
        }

        storagePlayerData(PLAYER_ID, PLAYER_DATA)

        return e.reply([
            '一键种植成功！',
            `种植了${plantedCount}块${VEGETABLE_NAME}`,
            FERTILIZER_NAME ? `使用了${plantedCount}个${FERTILIZER_NAME}` : '',
            `花费💰${totalPrice}`,
            `${CROP_DATA['plantingTime'].join('')}后可收获喵~`
        ].filter(Boolean).join('\n'))
    }
}